<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title></title>
    <link rel="icon" href="" type="image/x-icon" />
    <link href="/static/js/layui/css/layui.css" rel="stylesheet">
    <link href="/static/service/css/chat.css" rel="stylesheet">
    <style>
    .layui-tab-title .layui-this:after{
        border-left:0px;
    }
    </style>
</head>

<body>
    <header class="service-header">
        <div class="service-log">
            
        </div>
        <div class="service-title">客服工作台</div>
        <div class="service-status layui-text" style="height: 60px;line-height: 60px;color: #FFFFFF;">
            客服服务连接状态：<span class="layui-badge">正在连接</span>
        </div>
        <div class="service-info">
            <i class="layui-icon layui-icon-friends"></i>
            <span class="kefu">{$kefu['username']}</span>
            <span class="login-out">
                <a class="layui-text layui-btn layui-btn-danger layui-btn-sm"
                   href=" {:url('login/logOut')}">退出</a>
            </span>
        </div>
    </header>
    <div class="layui-row service-content">
        <div class="layui-col-xs1 service-menu">
            <!-- <div class="kefu-info">
                <button class="layui-btn layui-btn-danger onwork">开始上班</button>
                <button class="layui-btn layui-btn-danger offline" style="display: none;">我下班啦</button>
            </div> -->
            <div class="now-chat active">
                <i class="layui-icon layui-icon-dialogue"></i>
                <span>当前会话</span>
            </div>
            <!-- <div class="now-chat ">
                <i class="layui-icon layui-icon-dialogue"></i>
                <span>历史会话</span>
            </div> -->
        </div>

        <div class="layui-col-xs2 visitor-list" id="visitor-list">
           
        </div>
        <div class="layui-col-xs2 visitor-list" id="queue-list" style="display: none"></div>

        <div class="layui-col-xs7 service-chat-box">
            <div class="chat-container">
                <div class="layui-row chat-header" id="now-chat-box">
                    <div id="reLink" >
                        <i class="layui-icon layui-icon-release"></i>
                        <span>转接当前会话</span>
                    </div>
                    <div id="closeChat" style="display: none">
                        <i class="layui-icon layui-icon-close"></i>
                        <span>关闭当前会话</span>
                    </div>
                </div>
                <div class="layui-row chat-header" id="pre-link-box" style="display: none">
                    <div id="takeCare">
                        <i class="layui-icon layui-icon-dialogue"></i>
                        <span>接待访客</span>
                    </div>
                </div>

                <div class="layui-row chat-body" id="chat-area">
                    <!--接待中心-->
                </div>
                <div class="layui-row chat-footer">
                    <div class="text-holder">
                        <textarea id="textarea" placeholder="请输入"></textarea>
                    </div>
                    <div class="send-bar">
                        <div class="tool-box">
                            <i class="layui-icon layui-icon-face-smile" id="face" style="display: none;"></i>
                            <i class="layui-icon layui-icon-picture" id="image" style="display: none;"></i>
                        </div>
                        <div class="send-btn-div">
                            <input type="button" value="发送" class="send-input active" id="sendBtn" style="float: right;">
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="layui-col-xs2 service-bar">
            <div class="layui-tab layui-tab-brief"  style="margin: 0">
                <ul class="layui-tab-title">
                    <li class="layui-this">用户信息</li>
                    <li class="">快捷回复</li>
                </ul>
                <div class="layui-tab-content">
                    <div class="layui-tab-item layui-show">
                        <div class="message" style="margin-top: 16px">
                            <p>
                                <label>昵称：</label>
                                <input disabled="disabled" class="message-input" value="" id="nickname">
                            </p>
                        </div>
                        <div class="message" style="margin-top: 16px;display: none;">
                            <p>
                                <label>游客标示：</label>
                                <input disabled="disabled" class="message-input" value="" id="guest_code">
                            </p>
                        </div>
                        <div class="message" style="margin-top: 16px">
                            <p>
                                <label>IP地址：</label>
                                <input disabled="disabled" class="message-input" value="" id="ip_addr">
                            </p>
                        </div>
                        <div class="message" style="margin-top: 16px">
                            <p>
                                <label>地址：</label>
                                <input disabled="disabled" class="message-input" value="" id="address">
                            </p>
                        </div>
                    </div>
                    <div class="layui-tab-item ">
                        <table class="layui-table">
                            <thead>
                                <tr>
                                    <th>内容</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td>测试的</td>
                                    <td style="cursor: pointer;color: #01AAED" data-content="测试的" onclick="sendWord(this)"> 发送</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>

                </div>
            </div>
        </div>
    </div>

    <!-- 常用语 -->
    <div class="layui-row" id="word" style="display: none">
        <div class="layui-col-xs12">
            <table class="layui-table">
                <thead>
                    <tr>
                        <th>内容</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>测试的</td>
                        <td style="cursor: pointer;color: #01AAED" data-content="测试的" onclick="sendWord(this)"> 发送</td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
    <!-- 常用语 -->

    <!-- 转接提示层 -->
    <div class="layui-form" id="change-box" style="display: none">
        <div class="layui-form-item" style="margin-top: 20px">
            <div class="layui-tab layui-tab-brief">
                <ul class="layui-tab-title" id="change-group-title">

                </ul>
                <div class="layui-tab-content" id="relink-tab">

                </div>
            </div>
        </div>
    </div>
    <!-- 转接提示层 -->
    <div class="hide_wrap hidden" style="display: none;">
        <input type="hidden" name="ws" value="<= $ws; >">
        <input type="hidden" name="info" value='<= json_encode($info); >'>
        <!--游客头像列表-->
        <div class="visitor-card" id="xx-">
            <img src="" class="head-msg visitor-gray">
            <div class="msg">
                <p>
                    <span class="name">xx</span>
                    <span class="visitor-card-time">2019-04-02 16:51:41</span>
                </p>
                <p style="position: relative;"><span class="count" style="display: none;">0</span></p>
            </div>
        </div>
        <!--游客聊天内容wrap-->
        <div class="chat-box" id="ct-xxx" style="display: none;"></div>
        <!--游客聊天内容模板-->
        <div class="clearfloat guest_wrap">
            <div class="author-name">
                <small class="chat-date">2019-04-01 22:39:00</small>
            </div>
            <div class="right">
                <div class="chat-message">你好哇哈哈哈</div>
                <div class="chat-avatars"><img src=""></div>
            </div>
        </div>
        <!--客服聊天内容模板-->
        <div class="clearfloat my_wrap">
            <div class="author-name">
                <small class="chat-date">2019-04-02 16:51:48</small>
            </div>
            <div class="left">
                <div class="chat-avatars">
                    <img src="">
                </div>
                <div class="chat-message">dddd</div>
            </div>
        </div>
        <!--chat sep-->
        <div class="chat-sep" style="clear:both"></div>
    </div>
    <script src="/static/common/js/websocket.min.js"></script>
    <script src="/static/js/layui/layui.js"></script>
    <script>
        const info = {:json_encode($kefu)} || [];
        const options = {
            url: '{$socket}',
            pingTimeout: 15000,
            pongTimeout: 10000,
            reconnectTimeout: 5000,
            pingMsg: "ping",
            data: {
                'shop_id': info['shop_id']
                , 'code':info['code']
                , 'name':info['username']
                , 'avatar':info['avatar']
                , 'fid':info['code']
            }
        }
        var res = {};
        res.mine = options.data;
    </script>
    <script>
        layui.use(['layer','util','element'], function () {
            var $ = layui.$
                ,element=layui.element
                ,util=layui.util;
            var kf = new NbWebSocket(options);
            kf.onopen = (e) => {
                $(".service-header .service-status .layui-badge").addClass("layui-bg-green");
                $(".service-header .service-status .layui-badge").html("已连接");
                //cs_index_ops.kfConnect();
            }
            kf.onmessage = (e) => {
                if (e.data == 'pong') return; // 过滤心跳
                handlerMessage(e.data);
            }
            kf.onclose = function (res) {
                $(".service-header .service-status .layui-badge").removeClass("layui-bg-green");
                $(".service-header .service-status .layui-badge").html("已关闭");
                console.log('stkf_kf 已关闭');
            };
            // 发送
            $("#sendBtn").click(function () {
                kfSendMessage('');
            });
            var kfSendMessage = function send(inMsg) {
                if ('' == inMsg) {
                    var input = $("#textarea").val();
                } else {
                    var input = inMsg;
                }

                if (input.length == 0) {
                    return;
                }

                if (active_guest_code == null) {
                    return;
                }
                var kf_ele = $(".hide_wrap .my_wrap").clone();
                kf_ele.find(".author-name").html(util.toDateString(new Date().getTime(), 'yyyy-MM-dd HH:mm:ss'));
                kf_ele.find(".chat-message").html(input);
                kf_ele.find(".chat-avatars img").attr("src", info['avatar']);
                $("#ct-" + active_guest_code).append(kf_ele);
                $("#ct-" + active_guest_code).append($(".hide_wrap .chat-sep").clone());

                $("#textarea").val('');

                var active_guest = $("#q-" + active_guest_code);
                
                res.to ={
                        shop_id:info['shop_id'],
                        name: active_guest.attr("data-name"),
                        code: active_guest_code,
                        avatar: active_guest.attr("data-avatar"),
                        content: input,
                        source:'kf'
                    }
                kf.send(JSON.stringify({
                    type: 'chatMessage' //随便定义，用于在服务端区分消息类型
                    , data: res
                }));
               

                chat_box_ops.wordBottom();
            }

            var handlerMessage = function (res) {
                var data = JSON.parse(res);
                switch (data['message_type']) {
                    //初始化
                    case "get_user_info":
                        data.data.map(function (v, i, a) {
                            showGuestMessage(v);
                        });
                        break;
                        case "chatMessage":
                        showGuestMessage(data.data.to);
                        notifyAudio("/static/common/mp3/msn.mp3");  
                        break
                    case "guest_link":
                        showGuestMessage(data.data);
                        notifyAudio("/static/common/mp3/msn.mp3");  
                        break
                    case "closeDiff"://游客关闭
                        $("#q-" + data.data.code + " .head-msg").addClass("visitor-gray");
                        break
                }
            }
            var showGuestMessage = function (f_data) {
                var tmp_ele_id = f_data['code'];
                if ($("#visitor-list").find("#q-" + tmp_ele_id).size() < 1) {
                    var tmp_q_ele = $(".hide_wrap .visitor-card").clone();
                    tmp_q_ele.attr("id", "q-" + tmp_ele_id);
                    tmp_q_ele.attr("data-id", tmp_ele_id);
                    tmp_q_ele.attr("data-name", f_data['name']);
                    tmp_q_ele.attr("data-ip", f_data['f_ip']);
                    if (f_data.hasOwnProperty("appid")) {
                        tmp_q_ele.attr("data-appid", f_data['appid']);
                    }

                    tmp_q_ele.find(".msg .name").html(f_data['name']);
                    tmp_q_ele.find(".msg .visitor-card-time").html(f_data['date']);
                    tmp_q_ele.find(".head-msg").attr("src", f_data['avatar']);
                    $("#visitor-list").append(tmp_q_ele);
                }

                //有新消息来了就将头像变亮
                $("#q-" + tmp_ele_id + " .head-msg").removeClass("visitor-gray");
                //div 增加聊天内容
                if ($("#chat-area #ct-" + tmp_ele_id).size() < 1) {
                    var tmp_ct_ele = $(".hide_wrap .chat-box").clone();
                    tmp_ct_ele.attr("id", "ct-" + tmp_ele_id);
                    $("#chat-area").append(tmp_ct_ele);
                }
                // 未读条数计数有id则是历史信息
                let countPanel = $('#q-' + tmp_ele_id).find('.count');
                let num = countPanel.text();
                if(f_data.hasOwnProperty("id") && f_data.status == 0)  num = parseInt(num) + 1;
                if(f_data.hasOwnProperty("uid")) num = parseInt(num) + 1;
                num > 0 && countPanel.text(num).show();

                if (f_data['content']) {
                    var tmp_guest_ele = $(".hide_wrap .guest_wrap").clone();
                    tmp_guest_ele.find(".author-name").html(f_data['date']);
                    tmp_guest_ele.find(".chat-message").html(f_data['content']);
                    tmp_guest_ele.find(".chat-avatars img").attr("src", f_data['avatar']);
                    $("#chat-area #ct-" + tmp_ele_id).append(tmp_guest_ele);
                    $("#chat-area #ct-" + tmp_ele_id).append($(".hide_wrap .chat-sep").clone());
                }
                selectChatBox();
                if ($("#visitor-list .visitor-card").size() == 1) {
                    active_guest_code = tmp_ele_id;
                    $($("#visitor-list .visitor-card").get(0)).click();
                }
                chat_box_ops.wordBottom();
            }
            var selectChatBox = function () {
                $("#visitor-list .visitor-card").unbind("click"); // 防止事件叠加
                $("#visitor-list .visitor-card").click(function () {
                    $(this).removeClass('active').addClass('active').siblings().removeClass('active');
                    var guest_code = $(this).attr("data-id");
                    active_guest_code = guest_code;
                    $("#ct-" + active_guest_code).show().siblings().hide();
                    var tmp_select_target = $("#q-" + active_guest_code);
                    $(".service-bar #nickname").val(tmp_select_target.attr("data-name"));
                    $(".service-bar #ip_addr").val(tmp_select_target.attr("data-ip"));
                    //$(".service-bar #guest_code").val( active_guest_code );
                    $(this).find('.count').text('0').hide(); //清理未读提示
                    getChatLog(guest_code);
                });
            }
            var getChatLog = function (guest_code) {
                //获取游客的聊天记录
                if (typeof chat_log_cache == 'undefined') {
                    chat_log_cache = {};
                }

                if (chat_log_cache.hasOwnProperty(guest_code)) {
                    chat_box_ops.wordBottom();
                    return;
                }
                $.ajax({
                    url: '{:url('getChatLog')}',
                    data:{
                        guest_code:guest_code
                    },
                    dataType:'json',
                    success:function( res ){
                        chat_log_cache[ guest_code ] = 1;
                        if( res.code == 0 ){
                            return;
                        }
                        chat_box_ops.geneLogMessage( guest_code,res.data);

                    }
                });
                
            }
            var chat_box_ops = {
                geneLogMessage: function (guest_code, chat_log_list) {
                    var html_ = '';
                    var sep_ele = $(".hide_wrap .chat-sep").clone();
                    for (idx in chat_log_list) {
                        var f_data = chat_log_list[idx];
                        if (f_data['source'] == 'guest') {
                            var tmp_guest_ele = $(".hide_wrap .guest_wrap").clone();
                            tmp_guest_ele.find(".author-name").html(f_data['create_time']);
                            tmp_guest_ele.find(".chat-message").html(f_data['content']);
                            tmp_guest_ele.find(".chat-avatars img").attr("src", f_data['from_avatar']);
                            html_ = html_ + tmp_guest_ele.prop("outerHTML");
                        } else if (f_data['source'] == 'kf') {
                            var kf_ele = $(".hide_wrap .my_wrap").clone();
                            kf_ele.find(".author-name").html(f_data['create_time']);
                            kf_ele.find(".chat-message").html(f_data['content']);
                            kf_ele.find(".chat-avatars img").attr("src", f_data['from_avatar']);
                            html_ = html_ + kf_ele.prop("outerHTML");
                        }
                        html_ = html_ + sep_ele.prop("outerHTML");
                    }
                    html_ = html_ + $("#chat-area #ct-" + guest_code).html();
                    $("#chat-area #ct-" + guest_code).html(html_);
                    this.wordBottom();
                },
                wordBottom: function () {    // 滚动到最底端
                    var box = $(".chat-box:visible");
                    box.scrollTop(box[0].scrollHeight);
                }
            };
            function notifyAudio(url) {
                var turnAudio = document.getElementById("myWarnAudio");
                if (!turnAudio) {
                    turnAudio = document.createElement("audio");
                    document.body.appendChild(turnAudio);
                    turnAudio.id = "myWarnAudio";
                    turnAudio.controls = false;
                    turnAudio.loop = false;
                    turnAudio.hidden = true;
                }
                turnAudio.src = url;
                turnAudio.play();
            }
        });
    </script>
</body>

</html>